package health_system.health_system.websocket.Test;

import health_system.health_system.config.WebSocketConfigurator;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/test/ws", configurator = WebSocketConfigurator.class)
public class TestWebSocketServer {

    private static final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        String sessionId = session.getId();
        sessions.put(sessionId, session);
        log.info("New WebSocket connection: {}, current connections: {}", sessionId, sessions.size());
        log.info("Session parameters: {}", session.getRequestParameterMap());
        log.info("Session path parameters: {}", session.getPathParameters());
        
        try {
            session.getBasicRemote().sendText("Hello from WebSocket server!");
            log.info("Welcome message sent to session: {}", sessionId);
        } catch (IOException e) {
            log.error("Error sending welcome message", e);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        String sessionId = session.getId();
        log.info("Message from {}: {}", sessionId, message);
        
        try {
            session.getBasicRemote().sendText("Echo: " + message);
            log.info("Echo message sent to session: {}", sessionId);
        } catch (IOException e) {
            log.error("Error sending echo message", e);
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        String sessionId = session.getId();
        sessions.remove(sessionId);
        log.info("WebSocket connection closed: {}, reason: {}, current connections: {}", 
                sessionId, reason != null ? reason.getReasonPhrase() : "unknown", sessions.size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        String sessionId = session.getId();
        log.error("WebSocket error for session {}: {}", sessionId, error.getMessage(), error);
        sessions.remove(sessionId);
        
        // Try to close the session gracefully
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, 
                    "Error: " + error.getMessage()));
        } catch (IOException e) {
            log.error("Error closing session after error", e);
        }
    }
} 